const config = require('../config')
const axios = require('axios')
import vue from 'vue'
import { Message } from 'element-ui'
//网络错误码
function err(code) {
    switch (code) {
        case 200:
            return true;
        case 400:
            Message.error('错误请求')
            break;
        case 401:
            Message.error('未授权,请重新登录')
            break;
        case 403:
            Message.error('拒绝访问')
            break;
        case 404:
            Message.error('请求错误,未找到该资源')
            break;
        case 405:
            Message.error('请求方法未允许')
            break;
        case 408:
            Message.error('请求超时')
            break;
        case 500:
            Message.error('服务器出错')
            break;
        case 501:
            Message.error('网络未实现')
            break;
        case 502:
            Message.error('网络出错')
            break;
        case 503:
            Message.error('服务不可用')
            break;
        case 504:
            Message.error('网络超时')
            break;
        case 505:
            Message.error('http版本不支持该请求')
            break;
    }
    return
}
//拼接版本和检查是否传了必传参数
function getv(url, data, method) {
    console.log(url)
    //获取全部接口数据
    var init = JSON.parse(window.localStorage.getItem('init'))
    let arr = [];
    for (let i in init) {
        arr.push(init[i])
    }
    let reqinit = arr.filter(item => item.action == url)
    console.log(reqinit)
    console.log(reqinit[0])
    var index = reqinit[0].action.lastIndexOf('/')
    url = reqinit[0].action.slice(0, index + 1) + reqinit[0].edition + '_' + reqinit[0].action.slice(index + 1)
    console.log(url)
    /*取链接*/
    //拼接
    var canSend = true
    //默认不能发送请求的原因为空
    var noneData = []
    if (reqinit[0].must && reqinit[0].must != null) {
        if (reqinit[0].must.includes('token') && method == 'get') {
            //需要传token的将token加到传递的参数中
            data.token = config.get('userInfo').token
        }
        if (reqinit[0].must.includes('token') && method == 'post') {
            //需要传token的将token加到传递的参数中
            url = url + '?token=' + config.get('userInfo').token
        }
        //将必须的传参转为数组
        var must = reqinit[0].must.split(',')
        for (const i in must) {
            if (must[i] == 'token') {
                must.splice(i, 1)
            }
        }
        //如果must不为空
        if (must != null) {
            must.forEach(item => {
                //如果用户传递的参数包含must 那么能发送请求
                if (data[item]) {
                    canSend = true
                } else {
                    //如果不包含 将信息加入到不能请求的原因中
                    noneData.push(item)
                    //不能发送请求
                    canSend = false
                }
            })
        }
    }
    return { url: url, cansend: canSend, noneData: noneData, data: data }
}

//get请求
export const get = function (url, data, callback) {
    var uurl = url
    var urin = getv(url, data, 'get')
    url = urin.url
    console.log(url)
    if (urin.cansend) {
        var xmlget = new XMLHttpRequest()
        //定义数组保存请求时传的参数
        var str = []
        for (let i in urin.data) {
            str.push(i + '=' + urin.data[i])
        }
        //将参数数组转为字符串并用& 拼接
        str = str.join('&')
        //拼接url
        url = config.get('app_url') + url + '?' + str
        xmlget.open('get', url, true)
        //发送请求
        xmlget.send()
        //获取加载动画节点
        var load = document.getElementById('loading')
        //显示加载动画
        load ? load.className = 'block' : ''
        xmlget.onreadystatechange = function () {
            //请求完成
            if (xmlget.readyState == 4) {
                //隐藏加载动画
                load ? load.className = 'loadnone' : ''
                //请求返回的状态码
                err(xmlget.status)
                if (xmlget.status == 200) {
                    // var resdata = JSON.parse(xmlget.responseText)

                    // 
                    var resdata
                    try {
                        resdata = JSON.parse(xmlget.responseText)
                    }
                    catch (err) {
                        resdata = xmlget.responseText;
                    }

                 
                    //服务器返回的状态码
                    switch (resdata.code) {
                        case 200:
                            break;
                        case 401:
                            axios.get(config.get('a_url') + '/checkoutLoginType?key=' + config.get('userInfo').key + '&sertype=1')
                                .then(res => {
                                    if (res.data.code == 200) {
                                        get('index/index/login', { key: res.data.data.key }, res => {
                                            config.setUserInfo(res.data);
                                            get(uurl, data, res => {
                                                callback(res)
                                            })
                                        })
                                    } else {
                                        Message.error('登录信息失效,请重新登录')
                                        window.localStorage.clear()
                                        window.sessionStorage.clear()
                                        config.clear()
                                        vue.$router.push('/login')
                                    }
                                })
                            break;
                        case 499:
                            Message.error('未授权')
                            break
                        default:
                            //Message.error(resdata.data)
                            break;
                    }
                    callback(resdata)
                }
            }
        }
    } else {
        Message.error('缺少参数' + urin.noneData)
    }
}

//post请求
export const post = function (url, data, callback) {
    var uurl = url
    var urin
    if (data.params) {
        urin = getv(url, data.params, 'post')
    } else {
        urin = getv(url, data, 'post')
    }
    if (urin.cansend) {
        var xmlpost = new XMLHttpRequest()
        url = config.get('app_url') + url;
        xmlpost.open('post', url, true)
        if (data.header) {
            for (let i in data.header) {
                xmlpost.setRequestHeader(i, data.header[i]);
            }
        }
        xmlpost.send(urin.data)
        var load = document.getElementById('loading')

        load ? load.className = 'block' : ''
        xmlpost.onreadystatechange = function () {
            if (xmlpost.readyState == 4) {
                load ? load.className = 'loadnone' : ''
                err(xmlpost.status)
                if (xmlpost.status == 200) {
                    var resdata = JSON.parse(xmlpost.responseText)
                    //服务器返回的状态码
                    switch (resdata.code) {
                        case 200:
                            break;
                        case 401:
                            axios.get(config.get('a_url') + '/checkoutLoginType?key=' + config.get('userInfo').key + '&sertype=1')
                                .then(res => {
                                    if (res.data.code == 200) {
                                        get('index/index/login', { key: res.data.data.key }, res => {
                                            config.setUserInfo(res.data);
                                            post(uurl, data, res => {
                                                callback(res)
                                            })
                                        })
                                    } else {
                                        Message.error('登录信息失效,请重新登录')
                                        window.localStorage.clear()
                                        window.sessionStorage.clear()
                                        config.clear()
                                        vue.$router.push('/login')
                                    }
                                })
                            break;
                        case 499:
                            Message.error('未授权')
                            break;
                        default:
                            Message.error(resdata.data)
                            break;
                    }
                    callback(resdata)
                }
            }
        }
    } else {
        Message.error('缺少参数' + urin.noneData)
    }
}


